package com.hqq.leetcode.tree;

import com.hqq.exercise.tree.TreeNode;

/**
 * MinDepth 二叉树的最小深度
 * Description:
 * Given a binary tree, find its minimum depth.
 * <p>
 * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
 * Input:
 * -----1
 * ----/ \
 * ---2   3
 * ------/ \
 * -----4   5
 * Output:
 * 2
 * <p>
 * Created by heqianqian on 2017/9/13.
 */
public class MinDepth {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode rChild = new TreeNode(3);
        rChild.left = new TreeNode(4);
        rChild.right = new TreeNode(5);
        root.left = new TreeNode(2);
        root.right = rChild;

        MinDepth md = new MinDepth();
        System.out.println(md.minDepth(root));
    }

    /**
     * @param root: The root of binary tree.
     * @return An integer.
     */
    public int minDepth(TreeNode root) {
        // write your code here
        return depth(root);
    }

    private int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int lDep = depth(root.left);
        int rDep = depth(root.right);
        if (lDep == 0) {
            return rDep + 1;
        } else if (rDep == 0) {
            return lDep + 1;
        }
        return lDep < rDep ? lDep + 1 : rDep + 1;
    }
}
